﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// Performs a 'Postback' on the page after a given delay.
    /// </summary>
    public class AutoSubmit : Control, IPostBackEventHandler
    {
        public AutoSubmit()
        {
            DelayMilliseconds = 500;
        }

        public event EventHandler OnSubmit;

        public void RaisePostBackEvent(string eventArgument)
        {
            if (this.OnSubmit != null)
            {
                this.OnSubmit(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// The Amount of time to wait before a postback in milliseconds
        /// </summary>
        /// <value>
        /// Defaults to 500 msecs.
        /// </value>
        public int DelayMilliseconds { get; set; }
      
        protected override void OnPreRender(EventArgs e)
        {
            PostBackOptions pbo = new PostBackOptions(this);
            pbo.PerformValidation = false;

            ScriptManager.RegisterClientScriptBlock(this, typeof(AutoSubmit),
                "refreshScript", "setTimeout(\"" + Page.ClientScript.GetPostBackEventReference(pbo).Replace("'", "\'") + "\", " + DelayMilliseconds.ToString() + ")", true);
        }
    }
}
